using System;
using System.Collections.Specialized;
using System.Web;
using Twipler.App.Machine;
using Twipler.App.Parse.Code;

namespace Twipler.App.AsyncCommands
{
	public class ActionCommand : AsyncCommand
	{
		private readonly string _response;

		public ActionCommand(NameValueCollection collection)
		{
			string command = collection["do"];
			if (String.IsNullOrEmpty(command))
			{
				_response = "missing 'do' querystring";
				return;
			}

			TokenParser parser = new TokenParser(HttpUtility.UrlDecode(command));

			TokenParser.Result result = parser.Next(TokenParser.TokenType.StaticMethodCall);

			if ((result is TokenParser.ResultError) || (result is TokenParser.ResultEmpty))
			{
				_response = "could not parse 'do' querystring";
				return;
			}

			if (!(result.Value is StaticMethodCall))
			{
				_response = "'do' querystring is not a static method call";
				return;
			}

			if (Current.PageProducer == null)
				return;
            
			object obj = ((StaticMethodCall) result.Value).Invoke(Current.PageProducer.MachineEnvironment);
            
			_response = obj.ToString();

		}

		public override string Render()
		{
			return _response;
		}
	}
}